package com.meichis.yndms.ui.activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.EditorInfo;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.meichis.mcsappframework.dialog.DropDownPopupWindow;
import com.meichis.yndms.R;
import com.meichis.yndms.adapter.ClientAdapter;
import com.meichis.yndms.databinding.ActivityClientNearListBinding;
import com.meichis.yndms.model.ClientInfo;
import com.meichis.yndms.ui.common.BaseActivity;
import com.meichis.yndms.vm.ClientNearListVM;

import java.util.ArrayList;

public class ClientNearListActivity extends BaseActivity {

    private ActivityClientNearListBinding binding;
    private ClientNearListVM vm;
    private ClientAdapter adapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding.VLocation.setUpMap(savedInstanceState);
    }


    @Override
    protected void setDataBindingContentView() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_client_near_list);
        vm = new ViewModelProvider(this, new ViewModelProvider.NewInstanceFactory()).get(ClientNearListVM.class);
        binding.setVm(vm);
        binding.setClick(new ClickEvent());
        binding.setLifecycleOwner(this);
    }

    @Override
    protected void init() {
        vm.getShowDialog().setValue(true);
        binding.navigation.txtTitle.setText("门店拜访");
        binding.etSearch.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                vm.PageIndex = 0;
                adapter.clear();
                vm.GetNearRetailerList();
                return true;
            }
            return false;

        });
        binding.navigation.navBack.setOnClickListener(v -> {

            if (binding.navigation.funBtn.getText().equals("地图模式")) {
                onBackPressed();

            } else {
                binding.navigation.funBtn.setText("地图模式");
                binding.vfViewFlipper.setDisplayedChild(0);
            }
        });
        binding.navigation.funBtn.setText("地图模式");
        binding.navigation.funBtn.setOnClickListener(v -> {
            if (binding.navigation.funBtn.getText().equals("地图模式")) {
                binding.navigation.funBtn.setText("列表模式");
                binding.vfViewFlipper.setDisplayedChild(1);
                showRTInMap();
            } else {
                binding.navigation.funBtn.setText("地图模式");
                binding.vfViewFlipper.setDisplayedChild(0);
            }
        });

        addObserver();

        adapter = new ClientAdapter(getActivity(), R.layout.item_client_near_list_client, new ArrayList<>());
        binding.rvClient.setAdapter(adapter);
        binding.rvClient.setLayoutManager(new LinearLayoutManager(this));
        binding.rvClient.addOnScrollListener(scrollListener);
        binding.VLocation.setOnLocationChangedListener(aMapLocation -> {
            if (vm.getLocation() == null && !TextUtils.isEmpty(aMapLocation.getAddress())) {
                vm.setLocation(aMapLocation);
                vm.getShowDialog().setValue(false);
                binding.tvCity.setText("当前位置：" + aMapLocation.getDistrict() + aMapLocation.getStreet());
                vm.GetNearRetailerList();
            }
            return null;
        });

        //下拉刷新
        binding.swipTDPlist.setOnRefreshListener(() -> {
            binding.swipTDPlist.setRefreshing(false);
            vm.PageIndex = 0;
            adapter.clear();
            vm.GetNearRetailerList();
        });
    }

    private void addObserver() {
        vm.getShowDialog().observe(this, aBoolean -> showLoading(aBoolean));

        vm.getClientInfoList().observe(this, clientInfos -> {
            if (clientInfos.size() == 0) {
                showMsg("无更多门店数据");
                //无更多数据表示可以不可以上拉加载更多
                vm.isLoading = true;
            } else {
                adapter.addList(clientInfos);
                //有数据并且等于20表示也许还有数据可以继续上拉加载更多
                if (clientInfos.size() == 20) {
                    vm.isLoading = false;
                }
            }
        });
    }

    RecyclerView.OnScrollListener scrollListener = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            //获得recycleview的布局管理器,并判断是否是我们当前的设置的LinearLayoutManager
            RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
            if (manager instanceof LinearLayoutManager && !vm.isLoading) {
                //获得当前页面最后一个view的位置
                int lastPosition = ((LinearLayoutManager) manager).findLastVisibleItemPosition();
                //获得的位置和适配器的集合大小比较
                if (lastPosition == adapter.getItemCount() - 1) {
                    //表示当前正在加载
                    vm.isLoading = true;
                    //每次加载更多，页码为数据集合的大小
                    vm.GetNearRetailerList();
                }
            }
        }
    };

    private void showRTInMap() {
        try {
            binding.VLocation.getMap().clear();
            binding.VLocation.setLocationStyle();
        } catch (Exception e) {
        }
        for (ClientInfo m : vm.getClientInfoList().getValue()) {
            binding.VLocation.addMarker(m.getLatitude(), m.getLongitude(), 0, m.getFullName(), m.getAddress());
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (binding.VLocation != null) {
            binding.VLocation.onResume();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (binding.VLocation != null) {
            binding.VLocation.onPause();
            binding.VLocation.deactivate();
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (binding.VLocation != null) {
            binding.VLocation.onSaveInstanceState(outState);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (binding.VLocation != null) {
            binding.VLocation.Destroy();
        }
    }

    public class ClickEvent {

        public void Condition(View v) {
            new DropDownPopupWindow<>(ClientNearListActivity.this, R.drawable.bg_dropdown_light_left, "Name", vm.getDistanceList(), new DropDownPopupWindow.SelectedListener() {
                @Override
                public void setSelect(int position) {
                    binding.tvCondition.setText("距" + vm.getDistanceList().get(position).getName());
                    vm.setMaxDistance(vm.getDistanceList().get(position).getID());
                    GetNearRetailerList();
                }
            }).showAsDropDown(v);
        }

        public void GetNearRetailerList() {
            vm.PageIndex = 0;
            adapter.clear();
            vm.GetNearRetailerList();
        }

    }

}
